package com.tjian.fafa.user.base.myNetwork;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tjian.fafa.user.base.RegisterActivity;
import com.tjian.fafa.user.base.bean.ChatEntity;
import com.tjian.fafa.user.base.bean.UserInfo;
import com.tjian.fafa.user.base.chatServices.InitData;
import com.tjian.fafa.user.base.commons.GlobalMsgTypes;
import com.tjian.fafa.user.base.commons.GlobalStrings;
import com.tjian.fafa.user.base.mainBody.MainBodyActivity;
import com.tjian.fafa.user.module.user.CommonUser_fafa;
import com.tjian.util.StringUtil;
import com.tjian.util.TypeUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.Socket;

import static com.tjian.fafa.user.base.commons.GlobalMsgTypes.handShakeLogin_do;
import static com.tjian.util.StringUtil.bufferedReaderToString;
import static com.tjian.util.StringUtil.isInteger;

public class ClientListenThread extends Thread
{
    private Context context;
    private Socket socket;

    private InputStreamReader inputStreamReader;
    private BufferedReader bufferedReader;

    public ClientListenThread(Context par, Socket s)
    {
        this.context = par;
        this.socket = s;
        //printSocket(s);
    }

    //打印对象。
    public void printSocket(Socket printmSocket0)
    {
        try
        {
            InputStreamReader printmInStrRder0 = new InputStreamReader(printmSocket0.getInputStream());
            BufferedReader printmBuffRder0 = new BufferedReader(printmInStrRder0);
            String resp = null;
            while (true)
            {
                if ((resp = printmBuffRder0.readLine()) != null)
                {
                    int msgType = Integer.parseInt(resp);            // type of message received
                    String actualMsg = printmBuffRder0.readLine();
                    System.out.println("========,_20141228_185829,,actualMsg=" + actualMsg); //;
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void run()
    {
        super.run();
        try
        {
            //inputStreamReader = new InputStreamReader(this.socket.getInputStream());

            inputStreamReader = new InputStreamReader(this.socket.getInputStream(),"gbk");

            bufferedReader = new BufferedReader(inputStreamReader);


            String resp = null;

            //循环终止条件写true，这种情况，是需要在循环内主动终止循环的，要么使用return返回，要么使用break跳出循环。用在哪里呢？
            // 比如socket连接，服务端就需要一直等到客户端输入啊响应啊这么样的。
            while (true)
            {
                if ((resp = bufferedReader.readLine()) != null)
                {

                    boolean isInteger = StringUtil.isInteger(resp);

                    //如果是原来的通信方式
                    if (isInteger)
                    {

                        int msgType = Integer.parseInt(resp);
                        String actualMsg = bufferedReader.readLine();//ReadLine 方法可从 TextStream 文件中读取一整行字符，并以字符串返回结果。
                        //					actualMsg=haoren&#&1&#&1&#&1&#&1&#&1990&#&6&#&2&#&xx&#&xx&#&xx&#&
                        actualMsg = actualMsg.replace(GlobalStrings.replaceOfReturn, "\n");
                        switch (msgType)
                        {
                            case GlobalMsgTypes.msgPublicRoom:
                            case GlobalMsgTypes.msgFromFriend:    //2  lzp
                        /* try here to secure for the possible message with first input character as
                           "\n"	 */
                                uponReceivedMsg();

                                ChatEntity chatEntity = new ChatEntity(actualMsg);
                                Intent intent = new Intent("fafa.example.hello.MESSAGE_RECEIVED");
                                intent.putExtra("fafa.example.hello.msg_received", chatEntity.toString());
                                intent.putExtra("fafa.example.hello.msg_type", msgType);
                                this.context.sendBroadcast(intent);
                                break;
                            case GlobalMsgTypes.msgHandShake:
                                try
                                {
                                    UserInfo usrInfo = new UserInfo(actualMsg);
                                    InitData.getInitData().msgHandShakeArrive(usrInfo.toString());
                                }
                                catch (Exception e)
                                {
                                    e.printStackTrace();
                                }
                                break;
                            case GlobalMsgTypes.msgHandSHakeFriendList://5
                                try
                                {
                                    InitData.getInitData().msg5Arrive(actualMsg);
                                }
                                catch (Exception e)
                                {
                                    e.printStackTrace();
                                }
                                break;
                            case GlobalMsgTypes.msgUpdateFriendList:
                                Intent intentp = new Intent("fafa.example.hello.MESSAGE_RECEIVED");
                                intentp.putExtra("fafa.example.hello.msg_received", actualMsg);
                                intentp.putExtra("fafa.example.hello.msg_type", msgType);
                                this.context.sendBroadcast(intentp);
                                break;
                            case GlobalMsgTypes.msgSignUp:
                                RegisterActivity.getInstance().uponRegister(actualMsg);
                                break;
                            case GlobalMsgTypes.msgSearchPeople://9
                                MainBodyActivity.getInstance().onReceiveSearchList(actualMsg);
                                break;
                            case GlobalMsgTypes.msgFriendshipRequest:
                                uponReceivedMsg();
                                Intent intent2 = new Intent("fafa.example.hello.FRIEND_REQUEST_MSGS");
                                intent2.putExtra("fafa.example.hello.msg_received", actualMsg);
                                intent2.putExtra("fafa.example.hello.msg_type", msgType);
                                this.context.sendBroadcast(intent2);
                                break;
                            case GlobalMsgTypes.msgFriendshipRequestResponse:
                                uponReceivedMsg();
                                Intent intent3 = new Intent("fafa.example.hello.FRIEND_REQUEST_MSGS");
                                intent3.putExtra("fafa.example.hello.msg_received", actualMsg);
                                intent3.putExtra("fafa.example.hello.msg_type", msgType);
                                this.context.sendBroadcast(intent3);
                                break;
                            case GlobalMsgTypes.msgFriendGoOnline:
                                //	FriendListInfo.getFriendListInfo().friendGoOnAndOffline(actualMsg, 1);
                                Intent intent6 = new Intent("fafa.example.hello.MESSAGE_RECEIVED");
                                intent6.putExtra("fafa.example.hello.msg_received", actualMsg);
                                intent6.putExtra("fafa.example.hello.msg_type", msgType);
                                this.context.sendBroadcast(intent6);
                                break;
                            case GlobalMsgTypes.msgFriendGoOffline:
                                Intent intent7 = new Intent("fafa.example.hello.MESSAGE_RECEIVED");
                                intent7.putExtra("fafa.example.hello.msg_received", actualMsg);
                                intent7.putExtra("fafa.example.hello.msg_type", msgType);
                                this.context.sendBroadcast(intent7);
                                break;
                            default:
                                break;
                        }
                    }
                    else
                    {
                        //获取用户信息
                        if (GlobalMsgTypes.handShakeLogin_do.contentEquals(resp))
                        {
                            try
                            {
                                String message = bufferedReader.readLine();//ReadLine 方法可从 TextStream 文件中读取一整行字符，并以字符串返回结果。

                                //					actualMsg=haoren&#&1&#&1&#&1&#&1&#&1990&#&6&#&2&#&xx&#&xx&#&xx&#&
                                //actualMsg = actualMsg.replace(GlobalStrings.replaceOfReturn, "\n");
                                //InitData.getInitData().msgHandShakeArrive(commonUser_fafa.toString());

                                Type type = new TypeToken<CommonUser_fafa>()
                                {
                                }.getType();
                                Gson gson = new Gson();
                                CommonUser_fafa commonUser_fafa = gson.fromJson(message, type);

                                //InitData.getInitData().msgHandShakeArrive(commonUser_fafa.toString());

                                System.out.println("==========,_20161119_104519,\n" + TypeUtil.typeToString("commonUser_fafa", commonUser_fafa));
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                            break;
                        }
                    }
                }
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void uponReceivedMsg()
    {
        NetworkService.getInstance().sendUpload(GlobalMsgTypes.msgMsgReceived, "xxxxx");
    }

    public void closeBufferedReader()
    {
        try
        {
            bufferedReader = null;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
